package com.asmember;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * Helper class to use nmap application in subprocesses. Parses stdout from nmap
 * to list of reachable hosts in given subnet.
 * 
 * @author Grzegorz Matyszczak<BR>
 */
public class NmapHelper {
	
	public static List<String> getReachableHosts(String subnet) {
		List<String> result = new ArrayList<String>();
		try {
			System.out.println("Nmap subnet: "+subnet);
			ProcessBuilder processBuilder = new ProcessBuilder("nmap","-sP", subnet);
			processBuilder.redirectErrorStream(true);
			Process pr = processBuilder.start();  

		    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
		    String line;
		    String addr = null;
		    while ((line = in.readLine()) != null && !line.contains("Nmap done")) {
		        if(line.contains("Nmap scan report")) {
		        	if(line.contains("("))
		        		addr = line.substring(line.indexOf("(")+1, line.length()-1);
		        	else
		        		addr = line.substring("Nmap scan report for ".length());
		        }
		        else if(line.contains("up"))
		        	result.add(addr);
		    }
		    in.close();
			pr.destroy();
			System.out.println(line+"\n");
						
		} catch( Exception e ) {
			e.printStackTrace();
		}
		return result;
	}
	
}
